package io.xccit.common.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author CH_ywx
 * @date 2023-06-26
 * @description JWT工具类
 */
public class JwtHelper {

    //有效时间
    private static long tokenExpiration = 7 * 24 * 60 * 60 * 1000;
    //加密密钥
    private static String tokenSignKey = "xccit-auth";

    public static String createToken(Long userId, String username) {
        String token = Jwts.builder()
                .setSubject("AUTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("username", username)
                // 加密方式
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                // 压缩字符串
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    /**
     * 获取userID
     * @param token token
     * @return 用户ID
     */
    public static Long getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) return null;

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取用户名
     * @param token token
     * @return 用户名
     */
    public static String getUsername(String token) {
        try {
            if (StringUtils.isEmpty(token)){
                return "";
            }
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}